package com.qifan.energy.fragment;


import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qifan.energy.base.BaseFragment;
import com.qifan.energy.bean.result.CartListResult;
import com.qifan.energy.mvp.callback.IEventCallback;
import com.qifan.energy.R;
import com.qifan.energy.activity.ConfirmOrderActivity;
import com.qifan.energy.adapter.CartListAdapter;
import com.qifan.energy.global.Keys;
import com.qifan.energy.http.net.NetUtils;
import com.qifan.energy.http.response.MyObserver;
import com.qifan.energy.util.CheckUtil;
import com.qifan.energy.util.IntentUtils;
import com.qifan.energy.util.ToastUtils;
import com.qifan.energy.util.eventbus.EventBusUtils;
import com.qifan.energy.util.eventbus.EventCode;
import com.qifan.energy.util.eventbus.EventMessage;
import com.qifan.energy.widget.dialog.LoadingUtils;
import com.qifan.energy.widget.dialog.NormalCenterDialog;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class CartFragment extends BaseFragment {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.checkbox_iv)
    ImageView checkboxIv;
    @BindView(R.id.total_price_tv)
    TextView totalPriceTv;

    private CartListAdapter adapter;
    private List<CartListResult> dataList = new ArrayList();

    public static CartFragment newInstance() {
        return new CartFragment();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_cart;
    }

    @Override
    protected void initView(View view) {
        adapter = new CartListAdapter(dataList);
        /*adapter.setOnItemClickListener((a,v,p) -> {
            CartListResult result = (CartListResult)a.getData().get(p);
            Intent intent = new Intent();
            intent.putExtra(Keys.DETAIL_ID_KEY,result.getProductId());
            IntentUtils.startActivity(getActivity(), GoodsDetailActivity.class,intent);
        });*/
        /* 监听子控件点击 */
        adapter.setCheckCallback((isSelected,item)->{
            /*if (isSelected){
                boolean isSelectAll = true;
                for (CartListResult result :dataList){
                    if (!result.isSelected()) {
                        isSelectAll = false;
                        break;
                    }
                }
                checkboxIv.setSelected(isSelectAll);
            } else {
                checkboxIv.setSelected(isSelected);
            }*/
            for (CartListResult result :dataList){
                if (item.getId() != result.getId()){
                    result.setSelected(false);
                }
            }
            adapter.notifyDataSetChanged();
            //重新计算金额和赠送优惠券
            setUpUIWithData();
        });
        adapter.setCountCallback(isAdd -> {
            //重新计算金额和赠送优惠券
            setUpUIWithData();
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity())
                .sizeResId(R.dimen.dp_1)
                .colorResId(R.color.divider_color)
                .build());

        //添加空布局
        adapter.setEmptyView(getEmptyDataView());
    }

    /* 获取空布局 */
    private View getEmptyDataView() {
        return getLayoutInflater().inflate(R.layout.cart_list_empty, recyclerView, false);
    }

    @Override
    public void initData() {
        //注册EventBus
        EventBusUtils.register(this);
        cartList();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //注销EventBus
        EventBusUtils.unregister(this);
    }

    /**
     * 接收到分发的事件
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage event) {
        if (event.getCode() == EventCode.EVENT_1) {
            cartList();
        }
    }

    /* 购物车列表接口 */
    private void cartList(){
        NetUtils.cartList(new MyObserver<List<CartListResult>>(getActivity()) {
            @Override
            public void onSuccess(List<CartListResult> result) {
                dataList = result;
                //刷新
                adapter.setNewData(result);
                //UI赋值
                setUpUIWithData();
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /* UI赋值 */
    private void setUpUIWithData(){
        List<CartListResult> selectedList = new ArrayList();
        for (CartListResult result:dataList) {
            if (result.isSelected()){
                selectedList.add(result);
            }
        }
        //更改checkbox状态
        if (checkboxIv != null) {
            checkboxIv.setSelected(selectedList.size() == dataList.size() && selectedList.size() != 0);
            if (CheckUtil.hasContent(selectedList)){
                int quantity = 0;
                double totalPrice = 0.00f;
                int totalGiftGamePoint = 0;//游戏分
                double totalGiftTimeCard = 0.00f;//时间卡
                double totalGiftCouponAmount = 0.00f;//优惠券
                for (CartListResult result : selectedList){
                    quantity += result.getQuantity();
                    totalPrice += (result.getPrice() * result.getQuantity());
                    totalGiftGamePoint += (result.getGiftGamePoint() * result.getQuantity());
                    totalGiftTimeCard += (result.getGiftTimeCard() * result.getQuantity());
                    totalGiftCouponAmount += (result.getGiftCouponAmount() * result.getQuantity());
                }
                totalPriceTv.setText(String.format("%.02f元",totalPrice));
            } else {
                totalPriceTv.setText("0.00元");
            }
        }
    }

    /*@OnClick(R.id.delete_tv)
    void onDeleteTvClicked(){
        if (CheckUtil.isEmpty(dataList)) {
            ToastUtils.showShort("您暂时没有选中的购物车哦~");
            return;
        }
        //判断是否全删
        if (checkboxIv.isSelected()){//清空
            new NormalCenterDialog().showNow2(getParentFragmentManager(),"clear").title("确定清空购物车吗？").setEventCallback(new IEventCallback() {
                @Override
                public void onCancel() {
                    ToastUtils.showShort("取消");
                }
                @Override
                public void onComfirm() {
                    clearCartData();
                }
            });
        } else {//批量删
            new NormalCenterDialog().showNow2(getParentFragmentManager(),"delete").title("确定删除购物车吗？").setEventCallback(new IEventCallback() {
                @Override
                public void onCancel() {
                    ToastUtils.showShort("取消");
                }
                @Override
                public void onComfirm() {
                    deleteCartData();
                }
            });
        }
    }*/

    /* 清空购物车接口 */
    private void clearCartData(){
        List<CartListResult> selectedList = new ArrayList();
        for (CartListResult result:dataList) {
            if (result.isSelected()){
                selectedList.add(result);
            }
        }
        if (CheckUtil.isEmpty(selectedList)){
            ToastUtils.showShort("您暂时没有选中的购物车哦~");
            return;
        }
        LoadingUtils.show(getActivity());
        NetUtils.cartClear(new MyObserver<String>(getActivity()){
            @Override
            public void onSuccess(String result) {
                LoadingUtils.hide();
                ToastUtils.showShort("已清空!");

                /* 清空并刷新 */
                dataList.clear();
                adapter.notifyDataSetChanged();
                //更改checkbox状态
                if (checkboxIv != null) {
                    checkboxIv.setSelected(false);
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LoadingUtils.hide();
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /* 批量删除购物车接口 */
    private void deleteCartData(){
        List<Integer> selectedIds = new ArrayList();
        List<CartListResult> selectedList = new ArrayList();
        for (CartListResult result:dataList) {
            if (result.isSelected()){
                selectedIds.add(result.getId());
                selectedList.add(result);
            }
        }
        if (CheckUtil.isEmpty(selectedList)){
            ToastUtils.showShort("您暂时没有选中的购物车哦~");
            return;
        }
        LoadingUtils.show(getActivity());
        NetUtils.cartDelete(selectedIds, new MyObserver<String>(getActivity()) {
            @Override
            public void onSuccess(String result) {
                LoadingUtils.hide();
                ToastUtils.showShort("删除成功!");

                /* 批量删除并刷新 */
                dataList.removeAll(selectedList);
                adapter.notifyDataSetChanged();
                //更改checkbox状态
                if (checkboxIv != null) {
                    checkboxIv.setSelected(false);
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LoadingUtils.hide();
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    @OnClick(R.id.settle_tv)
    void onSettleTvClicked(){
        List<CartListResult> selectedList = new ArrayList();
        for (CartListResult result:dataList) {
            if (result.isSelected()){
                selectedList.add(result);
            }
        }
        if (CheckUtil.hasContent(selectedList)){
            /* 跳转页面 */
            Intent intent = new Intent();
            intent.putExtra(Keys.CART_ORDER_TYPE,(Serializable)selectedList);
            IntentUtils.startActivity(getActivity(), ConfirmOrderActivity.class,intent);
        } else {
            ToastUtils.showShort("您暂时没有选中的购物车哦~");
        }
    }

    @OnClick(R.id.select_all_ll)
    void onAllLlClicked(){
        /*if (CheckUtil.hasContent(dataList)){
            checkboxIv.setSelected(!checkboxIv.isSelected());
            for (CartListResult result :dataList){
                result.setSelected(checkboxIv.isSelected());
            }
            adapter.notifyDataSetChanged();
        }
        //重新计算金额和赠送优惠券
        setUpUIWithData();*/
    }
}
